package cn.yhp.chatgpt.data.domain.openai.service.rule.impl;

import cn.yhp.chatgpt.data.domain.openai.annotation.LogicStrategy;
import cn.yhp.chatgpt.data.domain.openai.model.aggregates.ChatProcessAggregate;
import cn.yhp.chatgpt.data.domain.openai.model.entity.MessageEntity;
import cn.yhp.chatgpt.data.domain.openai.model.entity.RuleLogicEntity;
import cn.yhp.chatgpt.data.domain.openai.model.valobj.LogicCheckTypeVO;
import cn.yhp.chatgpt.data.domain.openai.service.rule.ILogicFilter;
import cn.yhp.chatgpt.data.domain.openai.service.rule.factory.DefaultLogicFactory;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 敏感词过滤
 * @author yhp
 * @date 2024/2/7
 */
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.SENSITIVE_WORD)
public class SensitiveWordFilter implements ILogicFilter {

    @Value("${app.config.white-list}")
    private String whiteListStr;

    @Resource
    private SensitiveWordBs wordBs;

    @Override
    public RuleLogicEntity<ChatProcessAggregate> filter(ChatProcessAggregate chatProcess) throws Exception {
        // 1、白名单用户放行
        if (chatProcess.isWhiteList(whiteListStr)){
            return RuleLogicEntity.<ChatProcessAggregate>builder()
                    .type(LogicCheckTypeVO.SUCCESS).data(chatProcess).build();
        }
        // 2、根据用户问的问题，敏感过滤后，重新构造问题参数
        ChatProcessAggregate newChatProcess = new ChatProcessAggregate();
        newChatProcess.setOpenid(chatProcess.getOpenid());
        newChatProcess.setModel(chatProcess.getModel());

        List<MessageEntity> messageEntities = chatProcess.getMessages().stream().map(messageEntity -> {
            String content = messageEntity.getContent();
            String replace = wordBs.replace(content);
            return MessageEntity.builder()
                    .name(messageEntity.getName())
                    .role(messageEntity.getRole())
                    .content(replace)
                    .build();
        }).collect(Collectors.toList());
        newChatProcess.setMessages(messageEntities);
        // 返回过滤后的参数
        return RuleLogicEntity.<ChatProcessAggregate>builder()
                .type(LogicCheckTypeVO.SUCCESS).data(newChatProcess).build();
    }
}
